package com.u8.sdk;

import com.six7pay.sdk.SdkConfig;
import com.six7pay.sdk.SdkEvent;
import com.six7pay.sdk.UIHelper;
import com.six7pay.sdk.framework.base.log.HLog;
import com.six7pay.sdk.framework.base.notification.CallbackHandler;
import com.six7pay.sdk.framework.base.notification.EventNotifyCenter;
import com.six7pay.sdk.framework.base.utils.UtilsNetwork;
import com.six7pay.sdk.login.AccountMgr;
import com.six7pay.sdk.login.LoginCode;
import com.six7pay.sdk.login.LoginUserInfo;
import com.six7pay.sdk.login.Session;
import com.six7pay.sdk.login.ui.floatview.HlxFloatManager;
import com.six7pay.sdk.pay.OrderInfo;
import com.six7pay.sdk.pay.PayCode;
import com.six7pay.sdk.pay.PayMgr;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Handler;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.ViewGroup;

public class HLXSDK {

	enum SDKState {
		StateDefault, StateIniting, StateInited, StateLogin, StateLogined
	}
	private HlxFloatManager mHlxFloatManager;
	private static HLXSDK instance;
	private Activity GameActivity;
	private String appID;
	private boolean showExit = false;

	private Dialog myDialog;
	private Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			myDialog.dismiss();
		};
	};
	private static final String TAG = HLXSDK.class.getSimpleName();

	private void splash(Activity context) {
		int style = context.getResources().getIdentifier("wan51_u8_mydialog",
				"style", context.getPackageName());
		myDialog = new Dialog(GameActivity, style);
		View viewDialog = View.inflate(
				GameActivity,
				context.getResources().getIdentifier("wan51_yh_splash",
						"layout", context.getPackageName()), null);
		setParams(viewDialog);
		// myDialog.setContentView(context.getResources().getIdentifier(
		// "wan51_yh_splash", "layout", context.getPackageName()));
		myDialog.show();
		new Thread(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				try {
					Thread.sleep(2500);
					mHandler.sendEmptyMessage(0);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}).start();
	}

	// Venus
	private void setParams(View viewdialog) {
		Display display = GameActivity.getWindowManager().getDefaultDisplay();
		int width = display.getWidth();
		int height = display.getHeight();
		// 设置dialog的宽高为屏幕的宽高
		ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(width,
				height);
		myDialog.setContentView(viewdialog, layoutParams);
	}

	private HLXSDK() {

	}

	public static HLXSDK getInstance() {
		if (instance == null) {
			instance = new HLXSDK();
		}
		return instance;
	}

	private void parseSDKParams(SDKParams params) {
		this.appID = params.getString("AppID");
		if (null != appID) {
			Log.e("shanyou", "shanyou appid = " + appID);
		}
	}

	public void initSDK(Activity context, SDKParams params) {
		this.GameActivity = context;
		this.parseSDKParams(params);
		// splash(context);
		this.initSDK(context);
	}

	public void logout() {
		Log.d("U8SDK logout ", "logout");
		// ppsPlatform.iqiyiChangeAccount(GameActivity);
	}

	/**
	 * 必接功能<br>
	 * sdk初始化功能<br>
	 */
	public void initSDK(final Activity context) {

		EventNotifyCenter.add(SdkEvent.class, new CallbackHandler() {

			@EventNotifyCenter.MessageHandler(message = SdkEvent.EVENT_LOGIN)
			public void onLogin(LoginCode code, boolean fromLoginActivity) {
				HLog.info(this, "login result %d", code.getCode().Value());
				if (code.isSucc()) {
					if (mHlxFloatManager == null) {
						mHlxFloatManager = new HlxFloatManager(
								GameActivity);
						mHlxFloatManager.create();
					}

					AccountMgr.HlxToken hlxToken = AccountMgr.getInstance()
							.getToken();
					String key = hlxToken.key;
					
					U8SDK.getInstance().onLoginResult(encodeLoginResult(key,hlxToken.uid+"",hlxToken.device_code));
					/*HLog.info(TAG, "hlxtoken device_code: "
							+ hlxToken.device_code + "; key: " + hlxToken.key
							+ "; uid: " + hlxToken.uid + "; userInfo: "
							+ userInfo);
*/
				} else if (!fromLoginActivity) { // 如果 LoginActivity未显示
					if (!UtilsNetwork.isNetworkConnected(GameActivity)) {
						return;
					}
				}

				// 如果用户取消
				// if (code.isCancle()){}
			}

			@EventNotifyCenter.MessageHandler(message = SdkEvent.EVENT_PAY)
			public void onPay(PayCode code, String orderNo) {
				HLog.info(this, "pay result %d, orderNo(%s)", code.getCode()
						.Value(), orderNo);

				// 如果用户取消
				// if (code.isCancle()){}
			}

			@EventNotifyCenter.MessageHandler(message = SdkEvent.EVENT_VERIFY)
			public void onVerify(boolean ret, String msg) {
				HLog.info(this, "verify result %d, msg(%s)", ret ? 1 : 0, msg);
				UIHelper.toast(GameActivity, msg);
			}

			@EventNotifyCenter.MessageHandler(message = SdkEvent.EVENT_LOGOUT)
			public void onLogOut() {
				if (mHlxFloatManager != null) {
					mHlxFloatManager.destory();
					mHlxFloatManager = null;
				}
			}
		});

		U8SDK.getInstance().onResult(U8Code.CODE_INIT_SUCCESS, "init success");
	}

	private com.u8.sdk.LoginResult encodeLoginResult(String sign, String uid,String device_code) {
		String token = sign;// token 渠道SDK返回
		String spid = "six7";  // 后台配置
		String platform_id_uid = uid; // 渠道SDK返回
		String sdkVersion = "1.0";  //
		String appid = U8SDK.getInstance().getAppID();//固定调用方法
		Log.d("sy appid", "sy appid = " + appID);
		return new com.u8.sdk.LoginResult(token, spid, platform_id_uid, appid,
				sdkVersion,device_code);
	}

	public void login(final Activity context) {

		Log.d("PPSSDKPlatfrom login",
				"ppsLogin begin===========================================");
		if (!SDKTools.isNetworkAvailable(context)) {
			Log.e("manghuang ", "manghuang no net!!!");
			U8SDK.getInstance().onResult(U8Code.CODE_NO_NETWORK,
					"The network now is unavailable");

			return;
		}

		AccountMgr.getInstance().goToLoginActivity(GameActivity, false);
		Log.e("manghuang ", "manghuang  net!!!");
	}

	// 显示用户中心
	// public void showAccountCenter(){
	//
	// ppsPlatform.iqiyiAccountCenter(GameActivity);
	// }

	@SuppressLint("SimpleDateFormat")
	// private String getcode() {
	// SimpleDateFormat slp = new SimpleDateFormat("yyyyMMddHHmmss");
	// String st = slp.format(new Date(System.currentTimeMillis()));
	// return st;
	// }
	// 提交扩展数据
	public void submitExtendData(UserExtraData extraData) {
		// Toast.makeText(GameActivity, "提交数据成功....",Toast.LENGTH_SHORT).show();
		if (extraData.getServerID() == 0) {
			extraData.setServerID(1);
		}
		if (extraData.getDataType() == UserExtraData.TYPE_CREATE_ROLE) {
			// ppsPlatform.createRole(GameActivity,
			// "ppsmobile_s"+extraData.getServerID());
			// Log.d(TAG, "ppsmobile_s"+extraData.getServerID());
		} else if (extraData.getDataType() == UserExtraData.TYPE_ENTER_GAME) {
			// ppsPlatform.enterGame(GameActivity,
			// "ppsmobile_s"+extraData.getServerID());
			// Log.d(TAG, "ppsmobile_s"+extraData.getServerID());
		} else if (extraData.getDataType() == UserExtraData.TYPE_LEVEL_UP) {
		}
	}

	public void pay(Activity context, com.u8.sdk.PayParams data) {

		/*
		 * try { if(!isInited()){
		 * U8SDK.getInstance().onResult(U8Code.CODE_INIT_FAIL,
		 * "The sdk is not inited."); return; }
		 */
		if (!SDKTools.isNetworkAvailable(context)) {
			U8SDK.getInstance().onResult(U8Code.CODE_NO_NETWORK,
					"The network now is unavailable");
			return;
		}
		// ppsPlatform.iqiyiPayment(GameActivity, data.getPrice(),
		// data.getRoleId(), "ppsmobile_s1", data.getOrderKey());
		Log.e("huluxia pay",
				"hlx = " + data.getPrice() + "" + data.getProductName()
						+ "      orderid == " + data.getOrderID()
						+ "    orderkey == " + data.getOrderKey()
						+ "  product  ID ==" + data.getProductId());
		 if (!AccountMgr.getInstance().isLogin()) {
	            UIHelper.toast(GameActivity, "请先登录");
	            return;
	        }

		 
	        String token = Session.sharedSession().getToken();

	        OrderInfo orderInfo = new OrderInfo();
	        orderInfo.subject = data.getProductName();
	        orderInfo.body = data.getProductDesc();
	        orderInfo.amount = data.getPrice()+"";//银联方式最小金额是0.10
	        orderInfo.notifyUrl = SdkConfig.getInstance().getNotifyUrl();//该url由游戏方填写，在程序初始化时设置
	        orderInfo.orderNo = data.getOrderKey();

	        PayMgr.getInstance().goToPayActivity(context, orderInfo, token);
		/*
		 * } catch (Exception e) { e.printStackTrace(); }
		 */
	}

	/**
	 * 必接功能<br>
	 * 当游戏退出前必须调用该方法，进行清理工作。建议在游戏退出事件中进行调用，必须在游戏退出前执行<br>
	 * 如果游戏直接退出，而不调用该方法，可能会出现未知错误，导致程序崩溃<br>
	 */
	public void sdkExit(final Activity context) {
		if (showExit == true) {
			return;
		}
		Builder bd = new Builder(GameActivity);
		bd.setTitle("提示");
		bd.setMessage("确定退出游戏");
		bd.setCancelable(false);
		bd.setPositiveButton("确定", new OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				showExit = true;
				// TODO Auto-generated method stub
				GameActivity.finish();
			}
		});
		bd.setNegativeButton("取消", null);
		bd.show();

	}

}
